<template>
  <div class="tree">
    <el-tree
      ref="elTree"
      :data="data"
      show-checkbox
      node-key="编码"
      :check-strictly="false"
      :default-expanded-keys="[2, 3]"
      :default-checked-keys="defaultChecked"
      :props="defaultProps"
      :check-on-click-node="false"
      @check="check"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="typeof data['构件Id'] == 'string'"
            type="text"
            size="mini"
            @click="() => focus(data)"
          >
            <img src="../../image/icons/svg/icon_general_location.svg" alt="" />
            <!-- <svg-icon
              :icon-class="icon_general_location"
              class="icon-card"
            ></svg-icon> -->
          </el-button>
        </span>
      </span>
    </el-tree>
    <div class="blur"></div>
  </div>
  <!-- <div class="treewrap">
   
  </div> -->
</template>

<script>
// import treeData from "./index.json";
// import { arrayToTree, convertToTree } from "./tree";
// import icon_general_location from "../../image/icons/svg/icon_general_location.svg";
import Dayjs from "dayjs";
export default {
  props: {
    element: {
      type: Object,
    },
  },
  data() {
    return {
      data: null,
      defaultProps: {
        children: "children",
        label: "编码名称",
      },
      defaultChecked: null,
      AllIds: null,
      AllObjectId: null, //构建id映射表
      tileLayerId: "",
    };
  },
  computed: {},
  watch: {
    "element.data.treedata": {
      handler(val) {
        if (this.element.data.treedata) {
          this.init();
        }
      },
      deep: true,
    },
  },
  methods: {
    arrayToTree(data, type) {
      let result = [];
      let itemMap = {};
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        let id = type == "pid" ? item.id : item["编码"];
        let pid = type == "pid" ? item.pid : item["父节点编码"];
        if (!itemMap[id]) {
          itemMap[id] = {
            children: [],
          };
        }
        itemMap[id] = {
          ...item,
          children: itemMap[id]["children"],
        };
        let treeItem = itemMap[id];
        if (pid === null) {
          result.push(treeItem);
        } else {
          if (!itemMap[pid]) {
            itemMap[pid] = {
              children: [],
            };
          }
          itemMap[pid]["children"].push(treeItem);
        }
      }
      return result;
    },
    convertToTree(data) {
      let tempdata = data;
      for (let i = 0; i < tempdata.length; i++) {
        const item = tempdata[i];
        let path = item["编码"].split("-");
        if (path.length > 1) {
          item["id"] = path.join();
          item["pid"] = path.slice(0, path.length - 1).join();
        } else {
          item["id"] = path.join();
          item["pid"] = null;
        }
      }

      this.GetGanttData(tempdata);
      return this.arrayToTree(tempdata, "pid");
    },
    GetGanttData(data) {
      const result = [];
      for (let i = 0; i < data.length; i++) {
        const element = data[i];
        if (element["计划开始时间"]) {
          result.push({
            id: element.id,
            parent: element.pid,
            start_date: Dayjs(element["计划开始时间"]).format("DD-MM-YYYY"),
            open: true,
            text: element["编码名称"],
            duration: Dayjs(element["计划完成时间"]).diff(
              Dayjs(element["计划开始时间"]),
              "days"
            ),
            ...element,
          });
        }
      }
      console.log(result);
    },
    // 点击节点进行定位
    focus(data) {
      console.log(data);
      __g.tileLayer.focusActor(
        this.element.data.tilelayerid,
        data["构件Id"],
        10,
        1,
        [-45, 45, 0]
      );
      __g.tileLayer.highlightActor(
        this.element.data.tilelayerid,
        data["构件Id"]
      );
      setTimeout(() => {
        //停止所有Actor高亮
        __g.tileLayer.stopHighlightAllActors();
      }, 3000);
    },
    check(node, checkedNodes) {
      console.log("[ node ] >", node);
      console.log("[ checkedNodes ] >", checkedNodes);
      // console.log("[ this.ALLIds ] >", this.AllIds);
      let allcheckedKeys = [
        ...checkedNodes.checkedKeys,
        ...checkedNodes.halfCheckedKeys,
      ];
      // 并集 数组去重
      const RemoveSame = [...new Set([...allcheckedKeys, ...this.AllIds])];
      //数组交集，或得两个数组重复的元素
      let SamePart = allcheckedKeys.filter((item) =>
        this.AllIds.includes(item)
      );
      //差集=并集-交集  去除两个数组相同的元素
      let Difference = RemoveSame.filter((item) => !SamePart.includes(item));
      // console.log(Difference);

      if (this.AllIds.length > allcheckedKeys.length) {
        //
        console.log(this.AllObjectId, "AllObjectId");
        console.log("[ 需要隐藏 ] >", Difference);

        __g.tileLayer.hideActors([
          {
            id: this.element.data.tilelayerid,
            objectIds: Difference.map(
              (item) =>
                this.AllObjectId[item] && this.AllObjectId[item]["构件Id"]
            ).filter((i) => i),
          },
        ]);
      } else {
        console.log("[ 需要显示 ] >", Difference);
        __g.tileLayer.showActors([
          {
            id: this.element.data.tilelayerid,
            objectIds: Difference.map(
              (item) =>
                this.AllObjectId[item] && this.AllObjectId[item]["构件Id"]
            ).filter((i) => i),
          },
        ]);
      }
      this.AllIds = allcheckedKeys;
    },
    init() {
      if (this.element.data.style == "浅色") {
        this.$refs.elTree.$el.style.background = `rgba(255, 255, 255, 0.6)`;
        this.$refs.elTree.$el.style.color = `rgba(0, 0, 0, 1)`;
      } else {
        this.$refs.elTree.$el.style.background = `rgba(0, 0, 0, 0.6)`;
        this.$refs.elTree.$el.style.color = `rgba(255, 255, 255, 1)`;
        this.$refs.elTree.$el.style.border = `none`;
      }
      // console.log(this.element, "element");
      this.tileLayerId = this.element.data.tilelayerid;
      // let resulttreedata = arrayToTree(treeData);
      let resulttreedata = this.convertToTree(this.element.data.treedata); //扁平化数组转tree结构

      this.data = resulttreedata;
      this.defaultChecked = resulttreedata.map((i) => i["编码"]);

      const AllIds = [];
      const AllObjectId = {};
      this.element.data.treedata.forEach((item) => {
        AllIds.push(item["编码"]);
        if (item["构件Id"]) {
          AllObjectId[item["编码"]] = item;
        }
      });
      this.AllIds = AllIds;
      this.AllObjectId = AllObjectId;
    },
  },
  created() {},
  mounted() {
    this.init();
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  components: {},
};
</script>

<style lang="scss" scoped>
.tree {
  position: relative;
  width: 100%;
  height: 100%;
  .el-tree {
    // background: #00000000;

    height: 100%;
    // background: #000;
    // position: absolute;
    overflow-y: auto;
    // position: relative;
    border: 1px solid #fff;
    border-radius: 4px 4px 4px 4px;
    background: rgba(255, 255, 255, 0.6);
    padding: 15px 0;
    box-sizing: border-box;
    .custom-tree-node {
      img {
        left: 3px;
        top: 3px;
        cursor: pointer;
        position: relative;
        transition: all 0.3s;
      }
      img:hover {
        transform: scale(1.2);
      }
    }
  }

  .blur {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    z-index: -1;
    filter: blur(10px);
    // background: rgba(255, 255, 255, 0.6);
  }
}
</style>
<style>
.el-tree-node:focus > .el-tree-node__content {
  background: #00000000;
}
</style>
